package com.edisoncgh.controller;


import com.edisoncgh.pojo.Loan;
import com.edisoncgh.service.BookService;
import com.edisoncgh.service.LoanService;
import com.edisoncgh.pojo.User;
import com.edisoncgh.service.UserService;
import com.edisoncgh.service.impl.BookServiceImpl;
import com.edisoncgh.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/loan")
public class LoanController {
    @Autowired
    @Qualifier("LoanServiceImpl")
    private LoanService loanService;

    // 借阅展示页面
    @RequestMapping("/allLoan")
    public String list(Model model){
        List<Loan> list = loanService.findAllLoan();
        model.addAttribute("list", list);
        return "allLoan";
    }
    // 跳转到新增借阅页面
    @RequestMapping("/toAddLoan")
    public String toAddPaper() {
        return "addLoan";
    }

    // 新增借阅的请求
    @RequestMapping("/addLoan")
    public String addPaper(HttpServletRequest request/*, Model model*/) {
        // 创建借阅记录
        Loan loan = new Loan();
//        // 创建user服务对象
//        UserService userService = new UserServiceImpl();
//        // 创建book服务对象
//        BookService bookService = new BookServiceImpl();
//
//        // 判断借阅号存在与否
//        try {
//            int loanNo = Integer.parseInt(request.getParameter("loanNo"));
//            if (userService.findUserById(loanNo) == null) {
//                model.addAttribute("addLoanStatus", "借阅号不存在");
//                return "redirect:/loan/allLoan";
//            }
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }
//
//        // 判断目标图书存在与否
//        String isbn = request.getParameter("ISBN");
//        if (bookService.findBookById(isbn) == null) {
//            model.addAttribute("addLoanStatus", "借阅图书不存在");
//            return "redirect:/loan/allLoan";
//        }

        // 设置借阅者的借阅号
        loan.setLoanNo(Integer.parseInt(request.getParameter("loanNo")));
        // 设置目标图书isbn
        loan.setISBN(request.getParameter("ISBN"));
        // 默认设置为当前时间
        Date date = new Date();
        loan.setBorrowDate(date);
        // 插入当前新增的借阅记录
        loanService.addLoan(loan);
//        // 更新操作状态
//        model.addAttribute("addLoanStatus", "借阅成功");
        return "redirect:/view/allRecord";
    }

    // 删除借阅
    @RequestMapping("/deleteLoan")
    public String deleteLoan(Integer loanNo, String ISBN) {
        loanService.deleteLoan(loanNo, ISBN);
        return "redirect:/view/allRecord";
    }

}
